import 'package:flutter/material.dart';
import '../models/directory_model.dart';
import '../services/directory_service.dart';

class DirectoryPickerDialog extends StatefulWidget {
  final int currentDirectoryId;
  final String title;

  const DirectoryPickerDialog({
    Key? key,
    required this.currentDirectoryId,
    this.title = '选择目标文件夹',
  }) : super(key: key);

  @override
  State<DirectoryPickerDialog> createState() => _DirectoryPickerDialogState();
}

class _DirectoryPickerDialogState extends State<DirectoryPickerDialog> {
  final DirectoryService _directoryService = DirectoryService();
  bool _isLoading = true;
  String? _errorMessage;
  List<DirectoryModel> _directoryTree = [];
  int _selectedDirectoryId = 0;

  @override
  void initState() {
    super.initState();
    _loadDirectoryTree();
  }

  Future<void> _loadDirectoryTree() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final directoryTree = await _directoryService.getDirectoryTree();
      setState(() {
        _directoryTree = directoryTree;
        _selectedDirectoryId = widget.currentDirectoryId;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.title),
      content: SizedBox(
        width: double.maxFinite,
        height: 300,
        child:
            _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage != null
                ? Center(child: Text('加载失败: $_errorMessage'))
                : _buildDirectoryList(),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () => Navigator.pop(context, _selectedDirectoryId),
          child: const Text('确定'),
        ),
      ],
    );
  }

  Widget _buildDirectoryList() {
    // 添加根目录选项
    final List<dynamic> items = [
      {'id': 0, 'name': '根目录', 'isRoot': true},
      ..._directoryTree,
    ];

    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        final item = items[index];

        if (item is Map) {
          // 根目录特殊处理
          return _buildRootDirectoryItem(item);
        } else if (item is DirectoryModel) {
          return _buildDirectoryTreeItem(item, 0);
        }

        return const SizedBox.shrink();
      },
    );
  }

  Widget _buildRootDirectoryItem(Map item) {
    final int id = item['id'];
    final String name = item['name'];
    final bool isSelected = _selectedDirectoryId == id;

    return ListTile(
      leading: const Icon(Icons.folder, color: Colors.amber),
      title: Text(name),
      selected: isSelected,
      selectedTileColor: Colors.blue.withOpacity(0.1),
      onTap: () {
        setState(() {
          _selectedDirectoryId = id;
        });
      },
    );
  }

  Widget _buildDirectoryTreeItem(DirectoryModel directory, int level) {
    final bool isSelected = _selectedDirectoryId == directory.id;
    // 不能选择当前目录作为目标
    final bool isDisabled = directory.id == widget.currentDirectoryId;

    final List<Widget> children = [];

    // 添加当前目录项
    children.add(
      ListTile(
        leading: const Icon(Icons.folder, color: Colors.amber),
        title: Text(directory.name),
        selected: isSelected,
        selectedTileColor: Colors.blue.withOpacity(0.1),
        enabled: !isDisabled,
        onTap:
            isDisabled
                ? null
                : () {
                  setState(() {
                    _selectedDirectoryId = directory.id;
                  });
                },
        contentPadding: EdgeInsets.only(
          left: 16.0 + (level * 20.0),
          right: 16.0,
        ),
      ),
    );

    // 递归添加子目录
    if (directory.children != null && directory.children!.isNotEmpty) {
      for (final child in directory.children!) {
        children.add(_buildDirectoryTreeItem(child, level + 1));
      }
    }

    return Column(children: children);
  }
}
